var orderdata = '', orderId = '', rebackOrderReason = '', cheackorderParameter = null;
var tab_itemHeight = $('article').height() - 60;
var tab_listHeight = tab_itemHeight - 53 - 56 - 75 - 37.33;
var listSize = parseInt(tab_listHeight / 37.33) - 1;

$(function () {
    checkOrder.int("");

});
var aUserid = utils.storage.getter('aUserid')//获取登录用户
var checkOrder = {
    int: function (orderstatus) {
        SetBotoomIfon.init();//设置底部信息
        this.selectTr();
        this.search();
        this.getOrderdata;
        this.getOrderlist(orderstatus);
        this.switchOrderlist();
        utils.checkCache();//检测缓存是否丢失
        this.bottomEvent();
        //加载虚拟键盘组件
        widget.keyboard({
            target: '.keyboard'
        });
        /*历史账单时间选择*/
        var whenstart = {
            dateCell: '.getItemSellDetailStart',//input选择框
            skinCell: "jedateorange",//橙色风格
            format: 'YYYY-MM-DD hh:mm:ss',
            festival: true,//是否显示节日
            //maxDate: jeDate.now(0), //设定最大日期为当前日期
            isinitVal: true,                      //是否初始化时间，默认不初始化时间
            initAddVal: [0],                       //初始化时间，加减 天 时 分
            choosefun: function (elem, datas) {
                whenend.minDate = datas; //开始日选好后，重置结束日的最小日期
            }
        };
        jeDate(whenstart)
        var whenend = {
            dateCell: '.getItemSellDetailEnd',
            skinCell: "jedateorange",
            format: 'YYYY-MM-DD hh:mm:ss',
            festival: true,//是否显示节日
            maxDate: jeDate.now(0), //设定最大日期为当前日期
            choosefun: function (elem, datas) {
                whenstart.maxDate = datas; //将结束日的初始值设定为开始日的最大日期
            }
        };
        jeDate(whenend)


    },
    getOrderdata: {
        getData: function () {//获取接口数据
            $.ajax({
                url: _config.interfaceUrl.QueryOrderInfo + '' + aUserid + '/',
                type: "get",
                async: false,
                dataType: "text",
                success: function (data) {
                    orderdata = JSON.parse(data.substring(12, data.length - 3));//从第12个字符开始截取，到最后3位，并且转换为JSON
                }
            });
            return orderdata

        }

    },
    getOrderlist: function (orderstatus) {
        var that = this, data = null;
        $("#checklist tbody,#pagDome").html("");
        filtrateDatd();
        function filtrateDatd() {//数据筛选
            if (orderdata == "") {
                that.getOrderdata.getData();
            }
            data = orderdata.OrderJson;
            if (orderdata.Data == 1) {
                if (data.length == 0) {
                    $('#pagDome').hide()
                }
                else {
                    $('#pagDome').show()
                }
                if (orderstatus == "") {
                    data = data
                }
                if (orderstatus == "3") {
                    var arry = [];
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].orderstatus == 3) {
                            arry.push(data[i])
                        }
                    }
                    data = arry
                }
                if (orderstatus == "0") {
                    var arry = [];
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].orderstatus == 0) {
                            arry.push(data[i])
                        }
                    }
                    data = arry
                }
                /*如果数据为零结算，反结算，重印账单。会员交易凭条不能点击*/
                if (data.length < 1) {
                    $('.reprintCheck,.receipt,.c-mod-js,.c-mod-fjs').addClass('disabled').attr('disabled', true)
                }

                var orderNo = $.trim($("#orderNo").val())
                var deskNo = $.trim($("#deskNo").val())
                if (orderNo != "" || deskNo != "") {
                    var arry = [];
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].orderid.indexOf(orderNo) > -1 && data[i].tableName.indexOf(deskNo) > -1) {
                            arry.push(data[i])
                        }
                    }
                    data = arry;

                    //console.log(data)
                }

            }
        }

        $('#pagDome').pagination({
            dataSource: data,
            pageSize: listSize,
            showPageNumbers: false,
            showNavigator: true,
            callback: function (data, pagination) {
                //console.log(data)
                var str = "";
                for (var i = 0; i < data.length; i++) {
                    if (data[i].tabletype == '2' || data[i].tabletype == '3') {
                        if (data[i].memberno) {//判断是否是会员登录
                            str += '<tr type="out" orderid=' + data[i].orderid + ' orderstatus=' + data[i].orderstatus + ' memberno=' + data[i].memberno + ' personnum=' + data[i].custnum + ' tableno=' + data[i].tableName + '>';
                        }
                        else {
                            str += '<tr type="out" orderid=' + data[i].orderid + ' orderstatus=' + data[i].orderstatus + ' personnum=' + data[i].custnum + ' tableno=' + data[i].tableName + '>';
                        }
                    }
                    else {
                        if (data[i].memberno) {//判断是否是会员登录
                            str += '<tr type="in" orderid=' + data[i].orderid + ' orderstatus=' + data[i].orderstatus + ' memberno=' + data[i].memberno + ' personnum=' + data[i].custnum + ' tableno=' + data[i].tableName + '>';
                        }
                        else {
                            str += '<tr type="in" orderid=' + data[i].orderid + ' orderstatus=' + data[i].orderstatus + ' personnum=' + data[i].custnum + ' tableno=' + data[i].tableName + '>';
                        }
                    }

                    str += '   <td>' + data[i].orderid + '</td>'
                    var ordertype = '';
                    switch (data[i].orderstatus) {
                        case 0:
                            ordertype = "未结";
                            break;
                        case 3:
                            ordertype = "已结";
                            break;
                        case 2:
                            ordertype = "已取消";
                            break;
                        default:
                            ordertype = "未知";
                            break;
                    }
                    ;
                    str += '   <td>' + ordertype + '</td>'
                    str += '   <td>' + data[i].areaname + '</td>'
                    str += '   <td>' + data[i].tableName + '</td>'
                    str += '   <td>' + data[i].fullname + '</td>'
                    str += '   <td>' + (data[i].begintime).substring(8) + '</td>'
                    if (data[i].endtime === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + (data[i].endtime).substring(8) + '</td>'
                    }
                    str += '   <td>' + data[i].custnum + '</td>'
                    str += '   <td>' + data[i].dueamount + '</td>'
                    if (data[i].gzname === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gzname + '</td>'
                    }
                    if (data[i].gztele === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gztele + '</td>'
                    }
                    if (data[i].gzuser === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gzuser + '</td>'
                    }

                    str += "</tr>";
                }
                ;
                $("#checklist tbody").html(str);
                $("#checklist tr").eq(1).trigger("click")//默认选中第一行
            }
        });

    },
    switchOrderlist: function () {
        var that = this
        $(".check-type div").click(function () {//账单状态
            var orderstatus = $(this).attr("orderstatus");
            $(this).addClass("active").siblings("div").removeClass("active");
            that.getOrderlist(orderstatus)
        })
    },
    refreshOrderlist: function () {//刷新
        var that = this;
        var orderstatus = $(".check-type .active").attr("orderstatus");
        that.getOrderdata.getData();
        that.getOrderlist(orderstatus)
    },

    reprintCheck: function (msg) {//重印账单
        var orderidInfo=null
        if(msg){
            orderidInfo=msg
        }
        else {
            orderidInfo=orderId
        }
        $.ajax({
            url: _config.interfaceUrl.PrintPay + '/' + aUserid + '/' + orderidInfo + '/2/' + utils.storage.getter('posid') + '/',
            type: "get",
            success: function (data) {
                if (data.result == '0') {
                    rightBottomPop.alert({
                        content: "结账单打印完成",
                    })
                }
                else {
                    utils.printError.alert(data.msg)
                }

            }
        });
    },
    receipt: function () {//会员交易凭条
        Log.send(2, orderId+'会员交易凭条打印开始----');
        $.ajax({
            url: _config.interfaceUrl.PrintMemberSale + '/' + aUserid + '/' + orderId + '/' + utils.storage.getter('posid') + '/',
            type: "get",
            success: function (data) {
                if (data.result == '0') {
                    Log.send(2, orderId+'交易凭条打印成功');
                    rightBottomPop.alert({
                        content: "交易凭条打印完成",
                    })
                }
                else {
                    Log.send(2, orderId+'交易凭条打印成功'+JSON.stringify(data.msg));
                    utils.printError.alert(data.msg)
                }
            }
        });
    },
    rebackOrder: {//反结算跳转
        jumpfjs: function (user) {
            var memberAddress = JSON.parse(utils.storage.getter('memberAddress')),//会员地址
                vipType = utils.storage.getter('vipType');//会员类型1为餐道2为雅座
            /*餐道会员反结算*/
            if (cheackorderParameter.memberno && vipType == '1') {
                Log.send(2, cheackorderParameter.orderId+'获取餐道会员反结算获取会员订单信息开始----');
                $.ajax({
                    url: _config.interfaceUrl.GetOrderMemberInfo,//餐道会员获取订单会员信息
                    method: 'POST',
                    contentType: "application/json",
                    data: JSON.stringify({
                        'orderid': cheackorderParameter.orderId,
                    }),
                    dataType: "json",
                    success: function (data) {
                        $('#c-mod-fjs').modal("hide");
                        var rebackMemberinfo = data
                        if (rebackMemberinfo.cardno != undefined) {
                            Log.send(2, cheackorderParameter.orderId+'获取餐道会员反结算获取会员订单信息成功----：'+JSON.stringify(data));
                            Log.send(2, cheackorderParameter.orderId+'获取餐道会员反结算/餐道会员取消会员消费开始----传入参数：'+JSON.stringify({
                                    "Serial": rebackMemberinfo.orderid,//订单号
                                    "TraceCode": rebackMemberinfo.serial,//会员交易号
                                    "SUPERPWD": "",
                                    "cardno": rebackMemberinfo.cardno,//会员卡号
                                    "password": "",
                                    "branch_id": rebackMemberinfo.business,//租户id
                                    "securityCode": ""
                                }));

                            $.ajax({
                                url: memberAddress.vipcandaourl + _config.interfaceUrl.VoidSaleCanDao,//餐道会员取消会员消费
                                method: 'POST',
                                contentType: "application/json",
                                data: JSON.stringify({
                                    "Serial": rebackMemberinfo.orderid,//订单号
                                    "TraceCode": rebackMemberinfo.serial,//会员交易号
                                    "SUPERPWD": "",
                                    "cardno": rebackMemberinfo.cardno,//会员卡号
                                    "password": "",
                                    "branch_id": rebackMemberinfo.business,//租户id
                                    "securityCode": ""
                                }),
                                dataType: "json",
                                success: function (msg) {
                                    rebackMemberinfo.TraceCode = msg.TraceCode//重新赋值TraceCode会员交易号
                                    if (msg.Retcode != 0) {
                                        Log.send(4, cheackorderParameter.orderId+'获取餐道会员反结算/餐道会员取消会员消费失败----参数：'+JSON.stringify(msg));
                                        utils.printError.alert('会员消费反结算失败：' + msg.RetInfo)
                                    }
                                    else {
                                        Log.send(2, cheackorderParameter.orderId+'获取餐道会员反结算/餐道会员取消会员消费成功----参数：'+JSON.stringify(msg));
                                        rebackOrderOk(rebackMemberinfo)
                                    }
                                },
                            })
                        }
                        else {
                            Log.send(4, cheackorderParameter.orderId+'获取餐道会员反结算获取会员订单信息失败----参数：'+JSON.stringify(data));
                            utils.printError.alert('获取餐道会员反结算获取会员订单信息失败：' + data.RetInfo)

                        }
                    }
                })
            }
            /*雅座会员反结算*/
            if (cheackorderParameter.memberno && vipType == '2') {
                Log.send(2, cheackorderParameter.orderId+'雅座会员反结算开始----');
                $.ajax({
                    url: memberAddress.vipotherurl + _config.interfaceUrl.YaVoidSaleCanDao + cheackorderParameter.orderId + '/0/111111/',//雅座会员取消会员消费
                    type: "get",
                    dataType: "json",
                    success: function (msg) {
                        $('#c-mod-fjs').modal("hide");
                        if (msg.Data == '1') {
                            Log.send(2, cheackorderParameter.orderId+'雅座会员反结算成功----'+JSON.stringify(msg));
                            rebackOrderOk();
                        }
                        else {
                            utils.printError.alert(msg.Info)
                            Log.send(2, cheackorderParameter.orderId+'雅座会员反结算失败----'+JSON.stringify(msg));
                        }
                    }
                })
            }
            if (cheackorderParameter.memberno == undefined) {
                Log.send(2, cheackorderParameter.orderId+'没有使用会员反结算开始----');
                rebackOrderOk();
            }
            //会员反结结算成功后执行后台账单反结算
            function rebackOrderOk(rebackMemberinfo) {
                Log.send(2,'会员反结结算成功后执行后台账单反结算开始----参数：'+JSON.stringify({
                        'reason': rebackOrderReason,
                        'orderNo': orderId,
                        'userName': $.trim($("#user").val())
                    }));
                $.ajax({
                    url: _config.interfaceUrl.AntiSettlementOrder,//反结算
                    method: 'POST',
                    contentType: "application/json",
                    data: JSON.stringify({
                        'reason': rebackOrderReason,
                        'orderNo': orderId,
                        'userName': $.trim($("#user").val())
                    }),
                    dataType: "json",
                    success: function (data) {
                        //console.log(data)
                        $('#c-mod-fjs').modal("hide");
                        if (data.result === '0') {
                            $('#c-mod-fjs').modal("hide");
                            var _url = '../order.jsp?orderid=' + cheackorderParameter.orderId + '&personnum=' + cheackorderParameter.personnum + '&tableno=' + encodeURIComponent(encodeURIComponent(cheackorderParameter.tableno)) + '&referer=1&type=' + cheackorderParameter.type + ''
                            window.location.href = _url;
                            Log.send(2,'会员反结结算成功后执行后台账单反结算成功----跳转参数：'+JSON.stringify(_url));
                        }
                        else {

                            $('#c-mod-fjs').modal("hide");
                            if (rebackMemberinfo) {
                                Log.send(2,'会员反结结算成功后执行后台账单反结算失败----取消会员反结算：'+JSON.stringify({
                                        'cardno': rebackMemberinfo.cardno,//会员卡号,
                                        'deal_no': rebackMemberinfo.TraceCode,//会员反结算成功的交易号
                                        'tracecode': rebackMemberinfo.serial//会员反结算前的交易号
                                    }));
                                $.ajax({
                                    url: memberAddress.vipcandaourl + _config.interfaceUrl.UnVoidSale,//取消会员反结算
                                    method: 'POST',
                                    contentType: "application/json",
                                    data: JSON.stringify({
                                        'cardno': rebackMemberinfo.cardno,//会员卡号,
                                        'deal_no': rebackMemberinfo.TraceCode,//会员反结算成功的交易号
                                        'tracecode': rebackMemberinfo.serial//会员反结算前的交易号
                                    }),
                                    dataType: "json",
                                    success: function (msg) {
                                        if (msg.Retcode == '0') {
                                            utils.printError('反结算失败，请稍后再试')
                                            Log.send(4,'会员反结结算成功后执行后台账单反结算失败----取消会员反结算失败：'+JSON.stringify(msg));
                                        }
                                        else {
                                            utils.printError(msg.RetInfo);
                                            Log.send(4,'会员反结结算成功后执行后台账单反结算失败----取消会员反结算成功：'+JSON.stringify(msg));
                                        }
                                    }
                                })
                                return false
                            }
                            utils.printError('反结算失败，请稍后再试')
                            Log.send(2,'会员反结结算成功后执行后台账单反结算失败：'+JSON.stringify(data));
                        }

                    }
                })
            }

        },
        rebackOrder: function () {//反结算
            var that = this
            _getOrder();
            function _getOrder() {//二次确认弹窗
                var str = '<div class="js_Ok" style="text-align: left;">订单号：<br>' + orderId + '确定反结算吗？</div>';
                var alertModal = widget.modal.alert({
                    cls: 'fade in',
                    content: str,
                    width: 500,
                    height: 500,
                    title: "",
                    btnOkTxt: '确定',
                    btnOkCb: function () {
                        _getBackinfo();
                        $(".modal-alert:last,.modal-backdrop:last").remove();
                    },
                    btnCancelCb: function () {
                    }
                });
            };
            function _getBackinfo() {//获取是否生成清机单
                Log.send(2,'获取是否生成清机单开始----：');
                $.ajax({
                    url: _config.interfaceUrl.CheckAntiSettleOrder + '' + aUserid + '/' + orderId + '/',
                    type: "get",
                    dataType: "text",
                    success: function (data) {
                        data = JSON.parse(data.substring(12, data.length - 3));//从第12个字符开始截取，到最后3位，并且转换为JSON
                        // console.log(data)
                        Log.send(2,'获取是否生成清机单完成----：'+JSON.stringify(data));
                        if (data.Data == "0") {
                            _getClear(data.Info)
                        }
                        ;
                        if (data.Data == "1") {
                            _whyClear()
                        }
                    }
                });
            };
            function _getClear(info) {//已经生成清机单不能结业
                var str = '<div class="js_Ok" ><br>' + info + '</div>';
                var alertModal = widget.modal.alert({
                    cls: 'fade in',
                    content: str,
                    width: 500,
                    height: 500,
                    btnOkTxt: '',
                    btnCancelTxt: "确定",
                });
            };
            function _noChoiceClearReason() {//没有选择反结算原因
                var str = '<div class="js_Ok" ><br>请选择一个反结算原因</div>';

                var alertModal = widget.modal.alert({
                    cls: 'fade in',
                    content: str,
                    width: 500,
                    height: 500,
                    btnOkTxt: '确定',
                    btnCancelTxt: "",
                    btnOkCb: function () {
                        $(".modal-alert:last,.modal-backdrop:last").remove();
                    },
                    btnCancelCb: function () {
                    }
                });
            }

            function _whyClear() {
                var res = JSON.parse(utils.storage.getter('BACKSETTLE_REASON'));//获取反结算原因
                var str = '<div class="selectReason" style="text-align: left">'
                str += '<div class="form-group form-group-base form-input">'
                str += '   <span class="form-label" style="line-height: 40px">反结原因:</span>'
                str += '   <input id="selectReason" value="" name="selectReason" type="text" class="form-control" style="height: 40px;line-height: 40px;padding-left: 75px;width: 250px;" autocomplete="off">'
                str += '</div><br/>'
                str += '<div class="backListReason">'
                for (var i = 0; i < res.length; i++) {//反结算原因列表
                    str += '<label><input name="Fruit" type="radio" value=' + res[i].itemDesc + ' />' + res[i].itemDesc + '</label><br/>'
                }
                str += '</div></div>';
                var alertModal = widget.modal.alert({
                    cls: 'fade in',
                    content: str,
                    width: 500,
                    height: 500,
                    title: "请选择反结原因",
                    btnOkTxt: '确定',
                    btnOkCb: function () {
                        if ($("#selectReason").val() == "") {
                            _noChoiceClearReason();
                            return
                        }
                        $(".modal-alert,.modal-backdrop").remove();
                        $("#c-mod-fjs").load("../check/impower.jsp", {
                            "title": "反结算授权",
                            "userRightNo": "030203",
                            "cbd": "checkOrder.rebackOrder.jumpfjs(user)"
                        });
                        $("#c-mod-fjs").modal("show");
                    },
                    btnCancelCb: function () {

                    }
                });
                //选择给input赋值
                $(".selectReason input").click(function () {
                    $("#selectReason").val($(this).val());
                    rebackOrderReason = $("#selectReason").val();
                })
            };
        },
    },
    clearing: function () {//结算
        Log.send(2,cheackorderParameter.orderId+'账单结算开始------');
        var that = this,
            str = '<div class="js_Ok" style="text-align: left;">订单号：<br>' + cheackorderParameter.orderId + '确定结算吗？</div>',
            alertModal = widget.modal.alert({
                cls: 'fade in',
                content: str,
                width: 500,
                height: 500,
                title: "",
                btnOkTxt: '确定',
                btnOkCb: function () {
                    $(".modal-alert,.modal-backdrop").remove();
                    _clearingOk();
                },
                btnCancelCb: function () {
                }
            });

        function _clearingOk() {
            Log.send(2,cheackorderParameter.orderId+'账单结算判断是否有收银权限开始------'+JSON.stringify(aUserid));
            var userRight = utils.userRight.get(aUserid, "030206")//判断收银权限
            if (userRight) {
                var _url = '../order.jsp?orderid=' + cheackorderParameter.orderId + '&personnum=' + cheackorderParameter.personnum + '&tableno=' + encodeURIComponent(encodeURIComponent(cheackorderParameter.tableno)) + '&referer=1&type=' + cheackorderParameter.type + ''
                window.location.href = _url;
                Log.send(2,cheackorderParameter.orderId+'账单结算有收银权限跳转------'+JSON.stringify(_url));
            }
            else {
                that.errorAlert('您没有收银权限')
                Log.send(2,cheackorderParameter.orderId+'账单结算您没有收银权限------'+JSON.stringify(aUserid));
            }
        }

    },
    selectTr: function () {
        var that = this;
        $("body").on("click", "#checklist tr", function () {//点击tr变色
            $(this).addClass("tablistActive").siblings("tr").removeClass("tablistActive");
            var orderstatus = $.trim($(this).attr("orderstatus")),
                memberno = $(this).attr("memberno");
            orderId = $.trim($(this).attr("orderid"));
            if (memberno) {
                cheackorderParameter = {
                    'orderId': orderId,
                    'personnum': $.trim($(this).attr("personnum")),
                    'tableno': $.trim($(this).attr("tableno")),
                    'type': $.trim($(this).attr("type")),
                    'memberno': $.trim($(this).attr("memberno")),
                }
            }
            else {
                cheackorderParameter = {
                    'orderId': orderId,
                    'personnum': $.trim($(this).attr("personnum")),
                    'tableno': $.trim($(this).attr("tableno")),
                    'type': $.trim($(this).attr("type")),
                }
            }


            // console.log(memberno+","+orderId+","+orderstatus)
            if (orderstatus == "0") {
                $(".c-mod-fjs,.reprintCheck,.receipt").attr("disabled", "disabled").addClass("disabled");//反结算按钮，重印账单按钮disabled
                $(".c-mod-js").removeAttr("disabled", "disabled").removeClass("disabled");//结算按钮移除disabled
            }
            if (orderstatus == "2") {//订单已取消
                $(".c-mod-fjs,.reprintCheck,.receipt,.c-mod-js").attr("disabled", "disabled").addClass("disabled");//反结算按钮，重印账单按钮disabled
            }
            if (orderstatus == "3") {
                $(".c-mod-js").attr("disabled", "disabled").addClass("disabled");//结算按钮disabled
                $(".c-mod-fjs ,.reprintCheck,.receipt").removeAttr("disabled", "disabled").removeClass("disabled");//反结算按钮，重印账单按钮移除disabled
            }
            if (memberno && orderstatus == "3") {//判断是否存在会员登录并且已经结账才显示会员交易凭条
                $(".receipt").removeAttr("disabled").removeClass("disabled");
            }
            else {
                $(".receipt").attr("disabled", "disabled").addClass("disabled");
            }
            ;

        });
    },
    search: function () {
        var that = this;
        $('#orderNo,#deskNo').on('input propertychange focus', function () {
            var isHistory=$('.historyButton div').attr('isHistory');
            /*当班账单搜索*/
            if(isHistory=='true'){
                var orderstatus = $(".check-type .active").attr("orderstatus");
                that.getOrderlist(orderstatus)

            }
            /*历史账单搜索*/
            else {
                that.getHistoryOrderList();
            }
        });
    },
    bottomEvent: function () {
        var that = this, historyClickcont = 0;
        $(".foot-menu button").click(function () {
            var me = $(this);
            if (me.hasClass("refresh")) {//刷新
                that.refreshOrderlist();
            }
            if (me.hasClass("reprintClear")) {//重印清机单
                utils.reprintClear.get()
            }
            if (me.hasClass("reprintCheck")) {//重印账单
                that.reprintCheck()
            }
            if (me.hasClass("receipt")) {//会员交易凭条
                that.receipt()
            }
            if (me.hasClass("c-mod-fjs")) {//反结算
                that.rebackOrder.rebackOrder()
            }
            if (me.hasClass("c-mod-js")) {//反结算
                that.clearing()
            }
        });
        /*历史账单和当班账单切换*/
        $('.historyButton div').click(function () {
            $('#orderNo,#deskNo').val('');
            historyClickcont++
            var _this = $(this).attr('isHistory');
            if (_this == 'true') {
                $(this).attr('isHistory', false).text('当班账单');
                $('#dadaCheack').hide();
                $('#historyCheack').show();
                if (historyClickcont == 1) {
                    that.getHistoryOrderList();
                }

            }
            else {
                $(this).attr('isHistory', true).text('历史账单');
                $('#historyCheack').hide();
                $('#dadaCheack').show();
            }
        });
        /*历史账单时间选择*/
        $('.dataSelect-type .dataSelect').click(function () {
            var me = $(this),
                flag = me.attr("flag");
            me.addClass("active").siblings().removeClass('active');
            $("#historyChecklist tbody,#historypagDome").html("");
            if (flag == '4') {
                $('#getItemSellDetail-when').show();
                $('.getItemSellDetailStart').focus().val('');
                $('.getItemSellDetailEnd').val('');
                return false
            } else {
                $('#getItemSellDetail-when').hide();
                utils.loading.open('正在加载…')
                that.getHistoryOrderList();
            }
        })
        /*历史账单时间段选择查询按钮*/
        $('.historyQuery').click(function () {
            var beginTime = $.trim($('.getItemSellDetailStart').val()), endTime = $.trim($('.getItemSellDetailEnd').val());
            if (beginTime == '' || endTime == '') {
                utils.printError.alert('开始时间和结束时间不能为空');
                return false
            }
            if (Date.parse(new Date(endTime)) / 1000 - Date.parse(new Date(beginTime)) / 1000 < 0) {
                utils.printError.alert('开始时间不能大于结束时间');
                return false
            }
            utils.loading.open('正在加载…');
            setTimeout(function () {
                that.getHistoryOrderList();
            },300)

        })
        /*历史记录账单详情*/
        $("body").on("click", "#historyChecklist tbody tr", function () {
            $(this).addClass("tablistActive").siblings("tr").removeClass("tablistActive");
            var orderId = $.trim($(this).attr("orderid"));
            that.reckoningDialog(orderId)
        });
        /*打印账单详情*/
        $('#printHistoryCheck').click(function () {
            var orderid=$(this).attr('orderid');
            that.reprintCheck(orderid)
        })


    },
    getHistoryOrder: function () {
        var that = this, orderdata = null, historyOrderInfo = null, dateInfo = null, flag = null;
        flag = $('.dataSelect-type .dataSelect.active').attr('flag');
        dateInfo = that.dataSelect(flag);
        Log.send(2, '开始日期:'+dateInfo.beginTime+'结束日期:'+dateInfo.endTime+'历史账单数据列表查询开始——————');
        $.ajax({
            url: _config.interfaceUrl.getHistoryOrderInfo + '' + dateInfo.beginTime + '/' + dateInfo.endTime + '/',
            type: "get",
            async: false,
            dataType: "text",
            global:false,
            success: function (data) {
                Log.send(2, '开始日期:'+dateInfo.beginTime+'j结束日期:'+dateInfo.endTime+'历史账单数据列表查询成功返回参数：'+JSON.stringify(orderdata));
                orderdata = JSON.parse(data.substring(12, data.length - 3));//从第12个字符开始截取，到最后3位，并且转换为JSON
                if (orderdata.Data != '1') {
                    that.errorAlert('获取历史订单数据失败，请稍后重试');
                    utils.loading.remove();
                }
                else {
                    if (orderdata.OrderJson.length > 0) {
                        historyOrderInfo = orderdata.OrderJson;
                    }
                    else {
                        that.errorAlert('没有查询到符合条件的数据');
                        utils.loading.remove()
                    }
                }
            }
        });
        return historyOrderInfo

    },
    getHistoryOrderList: function () {
        var that = this, data = null;
        $("#historyChecklist tbody,#historypagDome").html("");
        filtrateDatd();
        function filtrateDatd() {//数据筛选
            data = that.getHistoryOrder();
            if (data == null) {
                return false
            }
            var orderNo = $.trim($("#orderNo").val())
            var deskNo = $.trim($("#deskNo").val())
            if (orderNo != "" || deskNo != "") {
                var arry = [];
                for (var i = 0; i < data.length; i++) {
                    if (data[i].orderid.indexOf(orderNo) > -1 && data[i].tableName.indexOf(deskNo) > -1) {
                        arry.push(data[i])
                    }
                }
                data = arry;
            }
        }
        if (data == null) {
            return false
        }
        $('#historypagDome').pagination({
            dataSource: data,
            pageSize: listSize,
            showPageNumbers: false,
            showNavigator: true,
            callback: function (data, pagination) {
                var str = "";
                for (var i = 0; i < data.length; i++) {
                    str += '<tr  orderid=' + data[i].orderid + '>';
                    str += '   <td>' + data[i].orderid + '</td>'
                    var ordertype = '';
                    switch (data[i].orderstatus) {
                        case 0:
                            ordertype = "未结";
                            break;
                        case 3:
                            ordertype = "已结";
                            break;
                        case 2:
                            ordertype = "已取消";
                            break;
                        default:
                            ordertype = "未知";
                            break;
                    }
                    ;
                    str += '   <td>' + ordertype + '</td>'
                    str += '   <td>' + data[i].areaname + '</td>'
                    str += '   <td>' + data[i].tableName + '</td>'
                    str += '   <td>' + data[i].fullname + '</td>'
                    str += '   <td>' + (data[i].begintime).substring(0) + '</td>'
                    if (data[i].endtime === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + (data[i].endtime).substring(0) + '</td>'
                    }
                    str += '   <td>' + data[i].custnum + '</td>'
                    str += '   <td>' + data[i].dueamount + '</td>';
                    var paywayname=data[i].paywayname;
                    if(paywayname === undefined){
                        str += '   <td></td>'
                    }
                    else {
                        if(data[i].paywayname.length>15){
                            paywayname=paywayname.substring(0,15)+'...'
                        }
                        str += '   <td>' + paywayname + '</td>'
                    }

                    /*if (data[i].gzname === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gzname + '</td>'
                    }
                    if (data[i].gztele === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gztele + '</td>'
                    }
                    if (data[i].gzuser === undefined) {
                        str += '   <td></td>'
                    }
                    else {
                        str += '   <td>' + data[i].gzuser + '</td>'
                    }*/

                    str += "</tr>";
                };
                $("#historyChecklist tbody").html(str);
                /*移除正在加载中*/
                setTimeout(function () {
                    utils.loading.remove();
                },500)

            }
        });


    },
    /*历史记录账单详情*/
    reckoningDialog:function (msg) {
        Log.send(2, msg+'历史账单详情查询开始——————');
        var that=this;
        $.ajax({
            url:_config.interfaceUrl.queryStatement,
            type: 'POST',
            dataType: 'json',
            data:{
                orderid: msg
            },
            success: function (res) {
                Log.send(2, msg+'账单详情查询成功返回参数：'+JSON.stringify(res));
                if(res.flag == 1){
                    initReckonTb(res.data)
                }else{
                    that.errorAlert(res.desc);
                }
            }
        })
        function initReckonTb(res){
            var data=res
            if(data != null){
                $("#branchname-show").text(data.branchname);
                $("#historyorderid").text(data.orderid);
                $("#tableno").text(data.area+'-'+data.tableno);
                $("#personnum").text(data.personnum);
                $("#waiter").text(data.waiter);
                $("#begintime").text(data.begintime);
                $("#endtime").text(data.endtime);

                var dishTr = '';
                //菜品
                if (data.dishes != null && data.dishes.length > 0) {
                    $.each(data.dishes, function(i, dish) {
                        dishTr += '<tr><td class="text">'
                            + dish.itemdesc + '</td><td>'
                            + dish.count + '</td><td>'
                            + dish.price
                            + '</td><td>'
                            + dish.amount + '</td></tr>';
                    });
                }
                //结算方式
                if (data.coupons != null && data.coupons.length > 0) {
                    dishTr += '<tr><td colspan="4"><hr class="dotted-line"/></td></tr>'
                        + '<tr><td>结算方式</td><td>金额</td><td colspan="2">备注</td></tr>';
                    $.each(data.coupons, function(i, coupon) {
                        dishTr += '<tr><td class="text">'
                            + coupon.name + '</td><td>' + coupon.amount
                            + '</td><td colspan="2">' + coupon.bankcardno
                            + '</td></tr>';
                    });
                }

                dishTr += '<tr><td colspan="4"><hr class="dotted-line" /></td></tr>'
                    + '<tr><td class="text">消费总额：</td> <td></td> <td class="right-align">'+data.totalconsumption+'</td><td></td></tr>';
                var colname = "抹零";
                if(data.payway == 20){
                    colname = "四舍五入";
                }
                dishTr += '<tr><td class="text">'+colname+'：</td> <td></td> <td class="right-align">'+data.payamount+'</td><td></td></tr>'
                    + '<tr><td class="text">赠送金额：</td> <td></td> <td class="right-align">'+data.giveamount+'</td><td></td></tr>'
                    + '<tr><td class="text">总优惠：</td> <td></td> <td class="right-align">'+data.couponamount+'</td><td></td></tr>'
                    + '<tr><td class="text">实收：</td> <td></td> <td class="right-align">'+data.paidamount+'</td><td></td></tr>'
                    // + '<tr><td class="text">开发票金额：</td> <td></td> <td class="right-align">'+data.invoiceamount+'</td><td></td></tr>';

                $('#printHistoryCheck').attr('orderid',data.orderid)
                $("#dishes-tb tbody").html(dishTr);
                $("#reckoning-dialog").modal("show");
            }
        }

    },
    /*快捷时间选择*/
    dataSelect: function (flag) {
        var nowdays = new Date(),
            year = nowdays.getFullYear(),
            month = nowdays.getMonth(),
            dateInfo = null;
        /*昨日*/
        if (flag == '1') {
            var AddDayCount = -1;
            var dd = nowdays;
            dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
            year = dd.getFullYear();
            month = dd.getMonth() + 1;//获取当前月份的日期
            var d = dd.getDate();
            if (d < 10) {
                d = '0' + d
            }
            year + "-" + month + "-" + d;
            dateInfo = {
                'beginTime': year + "-" + month + "-" + d + ' 00:00:01',
                'endTime': year + "-" + month + "-" + d + ' 23:59:59',
            }

        }
        ;
        /*本月*/
        if (flag == '2') {
            month = month + 1;
            if (month == 0) {
                month = 12;
                year = year - 1;
            }
            if (month < 10) {
                month = "0" + month;
            }
            var firstDay = year + "-" + month + "-" + "01";//本月的第一天
            var myDate = new Date(year, month, 0);
            var lastDay = year + "-" + month + "-" + myDate.getDate();//本月的最后一天
            var currentTime = utils.date.current()
            dateInfo = {
                'beginTime': firstDay + ' 00:00:01',
                'endTime': currentTime,
            }
        }
        ;
        /*上月*/
        if (flag == '3') {
            if (month == 0) {
                month = 12;
                year = year - 1;
            }
            if (month < 10) {
                month = "0" + month;
            }
            var firstDay = year + "-" + month + "-" + "01";//上个月的第一天
            var myDate = new Date(year, month, 0);
            var lastDay = year + "-" + month + "-" + myDate.getDate();//上个月的最后一天
            dateInfo = {
                'beginTime': firstDay + ' 00:00:01',
                'endTime': lastDay + ' 23:59:59',
            }
        }
        if (flag == '4') {
            dateInfo = {
                'beginTime': $.trim($('.getItemSellDetailStart').val()),
                'endTime': $.trim($('.getItemSellDetailEnd').val()),
            }
        }
        return dateInfo;

    },
    errorAlert: function (msg) {
        widget.modal.alert({
            cls: 'fade in',
            content: '<strong>' + msg + '</strong>',
            width: 500,
            height: 500,
            btnOkTxt: '',
            btnCancelTxt: '确定'
        });
    },
}